import React from "react"
import { Layout , Table , Button , Modal , Pagination , Form, Input, InputNumber, Select} from 'antd';

// 表单
import {
  DeleteOutlined,
  EditOutlined,
  PlusSquareOutlined
} from '@ant-design/icons';

import usersApi from "../api/usersApi"

const { Content } = Layout;





class Users extends React.Component{
  constructor(){
    super()
    this.state={
      columns: [
        {
          align:'center',
          title: '姓名',
          dataIndex: 'name',
          key: 'name',
          
        },
        {
          align:'center',
          title: '电话号码',
          dataIndex: 'phone',
          key: 'phone',
        },
        {
          align:'center',
          title: '住址',
          dataIndex: 'address',
          key: 'address',
        },
        {
          align:'center',
          title: '性别',
          dataIndex: 'sex',
          key: 'sex',
        },
        {
          align:'center',
          title: '头像',
          dataIndex: 'pic',
          key: 'pic',
          render:(pic)=>{
           return <img src={pic} style={{width:"50px", height: "50px"}} />
          }
        },
        {
          align:'center',
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          render:(action, row)=>{
            return(
              <React.Fragment>
                <Button type="primary" onClick={this.showModal.bind(this,row)} icon={<EditOutlined />}>编辑</Button>
                <Button type="danger" icon={<DeleteOutlined /> } onClick={this.showdel.bind(this,row._id)}>删除</Button>
              </React.Fragment>
              
            )
          }
        },
      ],
      // 数据渲染
      dataSource: [],
      // 第几页
      page: 1,
      // 一页多少条
      pagesize:10,
      // 一共有多少条数据
      total: 0,
      // 查询条件
      search:{},
      // 编辑弹出框
      visible: false,
      // 弹出框显示编辑还是新增
      titleCheck: true,
      // 点击删除弹框
      dleisOK:false,
      // 记录id删除
      uid:'',
      // 编辑打开表单显示
      // 地址
      address: [],
      // 姓名
      name: "",
      // 电话号码
      phone: "",
      // 性别
      sex: "",
    }

    
  }

  // 编辑按钮打开
  showModal = (row) => {
    console.log(row.address)
    let {address,name,phone,sex} = this.state
    address=row.address
    console.log(address)
    // this.state.visible= true,
    this.setState({
      titleCheck: true,
      visible:true,
      address
    })
    // this.setState({
    //    address,
    // name:row.name,
    // phone: row.phone,
    // sex: row.sex,
     
    //   titleCheck: true,
    //   visible: true,
      
    // });
  };
  // 确定编辑
  handleOk = e => {
    // console.log(e);
    this.setState({
      visible: false,
    });
  };
  //取消编辑
  handleCancel = e => {
    // console.log(e);
    this.setState({
      visible: false,
    });
  };
  


  // 拿数据
  async getdata(){
    let {page,pagesize,search} = this.state
    try{
      let p =await usersApi.getUserList(page,pagesize,search)
      let arr = p.data.data
      arr.forEach(item=>{
        item.key=item._id
      })
      this.setState({
        dataSource:arr,
        total:p.data.total
      })
    }catch(err){
      console.log(err)
    }
    
  }
  // 打开页面的时候渲染页面
  componentDidMount(){
    this.getdata()
    const { setFieldsValue } = this.props.form;
    // 这里就能实现指定表单设置value
    setTimeout(()=>{
        setFieldsValue({"username": "Tom"})
    },5000)
  }
  // 接收多少分页的变动
  onCheckPage(page, pagesize){
    this.setState({
      page,
      pagesize

    },()=>{
      this.getdata()
    })
  }
  // 打开新增
  add(){
    this.setState({
      address:"",
      name:"",
      phone:"" ,
      sex: "", 
      titleCheck: false,
      visible: true,
      
    });
  }
  // 删除对话框弹出
  showdel = (uid) => {
    
    this.setState({
      uid,
      dleisOK: true,
    });
  };
  // 确定删除
  hideModal = () => {
     usersApi.deluser(this.state.uid)
     this.getdata()
    this.setState({
      dleisOK: false,
    });
  };
  // 取消删除
  calloff(){
    this.setState({
      dleisOK: false,
    });
  }
  




  render(){
    
    const layout = {
      labelCol: {
        span: 8,
      },
      wrapperCol: {
        span: 16,
      },
    };
    const validateMessages = {
      required: '${label} is required!',
      types: {
        email: '${label} is not validate email!',
        number: '${label} is not a validate number!',
      },
      number: {
        range: '${label} must be between ${min} and ${max}',
      },
    };
    
     
     const onFinish = values => {
        console.log(values);
      };
   
      // 选择器(男女)
      const { Option } = Select
      function handleChange(value) {
        console.log(`selected ${value}`);
      }
    return(
      
      <div>
        
        {/* 新增按钮 */}
        <Button type="danger" onClick={this.add.bind(this)} size="large" icon={<PlusSquareOutlined />}>
           新增用户
        </Button>

        <Content style={{ overflow: 'initial' }}>
        <Table dataSource={this.state.dataSource} columns={this.state.columns} pagination={false} />
        <div style={{textAlign:"center",marginTop: "30px"}}>
          <Pagination defaultCurrent={1} total={this.state.total} onChange={this.onCheckPage.bind(this)} />
        </div>
        </Content>
        
      

        {/* 点击新增弹出框 */}
        <Modal
          title={this.state.titleCheck?"编辑用户":"新增用户"}
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          {/* 点击弹出编辑 */}
          <Form {...layout} name="nest-messages" onFinish={onFinish} validateMessages={validateMessages}>
      <Form.Item
        name={['user', 'name']}
        label="姓名"
        rules={[
          {
            required: true,
          },
        ]}
        initialValue={this.state.titleCheck?this.state.name:""}
      >
        <Input/>
      </Form.Item>
      <Form.Item
        name={['user', 'phone']}
        label="手机号码"
        rules={[
          {
            pattern:/^[1]([3-9])[0-9]{9}$/,
            message: "手机号码错误"
          },{
            required: true,message:"请输入电话号码"
          }
          
        ]}
        initialValue={this.state.titleCheck?this.state.phone:""}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name={['user', 'sex']}
        label="请选择性别"
        rules={[
          {required: true, message: '请选择性别'}
        ]}
        initialValue={this.state.titleCheck?this.state.sex:""}
      >
        <Select style={{ width: 120 }} onChange={handleChange} >
          <Option value="girl">女</Option>
          <Option value="man">男</Option>
        </Select>
      </Form.Item>
      <Form.Item name={['user', 'address']} label="住址" initialValue={this.state.titleCheck?this.state.address:""}>
        <Input.TextArea />
      </Form.Item>
      
    </Form>
        
        </Modal>
        
        {/* 确定删除弹出框 */}
        <Modal
          title="点击确定会永久删除"
          visible={this.state.dleisOK}
          onOk={this.hideModal}
          onCancel={this.calloff.bind(this)}
          okText="确认"
          cancelText="取消"
        >你确定要删除他吗</Modal>

      </div>
    )
    
  }

}

export default Users